import axios, { AxiosResponse } from 'axios'
import type { AxiosInstance, AxiosRequestConfig } from 'axios'
import { IDataType } from '@/service/types'
import {
  IJJRequestConfig,
  IJJRequestInterceptor
} from '@/service1/request/types'

class JJRequest {
  instance: AxiosInstance
  interceptors?: IJJRequestInterceptor

  constructor(config: IJJRequestConfig) {
    // config.transformResponse = (res) => {
    //   const result = JSON.parse(res)
    //   console.log(result)
    //   return result
    // }
    this.instance = axios.create(config)
    this.interceptors = config.interceptors

    this.instance.interceptors.request.use(
      (config) => {
        console.log('全局请求拦截,封装顺序1')
        return config
      },
      (error) => {
        console.log('全局请求失败拦截', error)
      }
    )
    this.instance.interceptors.response.use(
      (res) => {
        console.log('全局响应拦截,封装顺序1')
        return res.data
      },
      (error) => {
        console.log('全局响应失败拦截')
        console.log(error.request)
        console.log(error.response)
        return error
      }
    )

    this.instance.interceptors.request.use(
      this.interceptors?.requestInterceptor,
      this.interceptors?.requestInterceptorCatch
    )
    this.instance.interceptors.response.use(
      this.interceptors?.responseInterceptor,
      this.interceptors?.responseInterceptorCatch
    )
  }

  request<T>(config: IJJRequestConfig<T>): Promise<T> {
    return new Promise<T>((resolve, reject) => {
      //请求拦截
      if (config.interceptors?.requestInterceptor) {
        config = config.interceptors.requestInterceptor(config)
      }

      this.instance
        .request<any, T>(config)
        .then((res) => {
          if (config.interceptors?.responseInterceptor) {
            res = config.interceptors.responseInterceptor(res)
          }
          resolve(res)
        })
        .catch((err) => {
          console.log('=====', err)
          reject(err)
        })
    })
  }
}

export default JJRequest
